import React, {Component} from 'react'
/**
 *JsonUitl的实现
 */
class JsonUtils extends React.Component {

  /**
     *字符串转json
     *
     */
  static stringToJson(data) {
    return JSON.parse(data);
  }
  /**
     *json转字符串
     */
  static jsonToString(data) {
    return JSON.stringify(data);
  }
  /**
     *map转换为json
     */
  static mapToJson(map) {
    return JSON.stringify(JsonUtils.strMapToObj(map));
  }
  /**
     *json转换为map
     */
  static jsonToMap(jsonStr) {
    let json
    try{
      json = JSON.parse(jsonStr);
    }catch(e){
      json = jsonStr;
    };
    return JsonUtils.objToStrMap(json);
  }

  /**
     * json 转 URLSearchParams
     * @param jsonStr
     */
  static jsonToParam(jsonStr) {
    return this.mapToParam(JsonUtils.jsonToMap(jsonStr))
  }

  /**
     * map 转 URLSearchParams
     * @param strMap
     * @returns {URLSearchParams}
     */
  static mapToParam(strMap) {
    var params = new URLSearchParams();
    for (let [k, v] of strMap) {
      params.append(k, v);
    }
    return params;
  }

  /**
     *map转化为对象（map所有键都是字符串，可以将其转换为对象）
     */
  static strMapToObj(strMap) {
    let obj = Object.create(null);
    for (let [k, v] of strMap) {
      obj[k] = v;
    }
    return obj;
  }

  /**
     *对象转换为Map
     */
  static objToStrMap(obj) {
    let strMap = new Map();
    for (let k of Object.keys(obj)) {
      strMap.set(k, obj[k]);
    }
    return strMap;
  }

  /**
     * param转json
     * @param mp
     * @returns {{}}
     */
  static paramMapToJson(mp) {
    let strMap = {};
    for (let [k, v] of mp) {
      let klist = k.split(".")
      klist.forEach(key => {
        let tempMap = strMap
        klist.forEach(ky => {
          let val = strMap[ky];
          if (val == undefined) {
            if (ky != klist[klist.length - 1]) {
              tempMap[ky] = {};
              tempMap = tempMap[ky]
            } else {
              tempMap[ky] = v;
            }
          } else {
            tempMap = tempMap[ky]
          }
          if (key == ky)
            return
        })
      })
    }
    return this.jsonToParam(JSON.stringify(strMap));
  }

}

export default JsonUtils;
